package com.zlm.udpThread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @Author: 郑
 * UDP接受数据类
 */
public class UdpReceive implements Runnable{
    boolean flag = true;
    private DatagramSocket socket = null;
    private DatagramPacket dataPacket = null;

    private int fromPort;
    private String fromName;

    public UdpReceive(int fromPort,String fromName) {
       this.fromPort = fromPort;
       this.fromName = fromName;
        try {
            socket = new DatagramSocket(fromPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {

        try {
            while (flag) {
                //准备数据包
                byte[] bytes = new byte[1024];
                dataPacket = new DatagramPacket(bytes, 0, bytes.length);
                socket.receive(dataPacket);

                byte[] data = dataPacket.getData();
                String receiveData = new String(data, 0, data.length);

                System.out.println(fromName+"："+receiveData);
                //必须要去空格
                if(receiveData.trim().equals("bye")){
                    flag = false;
                }

            }
        } catch (IOException e) {


        }

        socket.close();
    }
}
